/*************************************************************************
	> File Name: mypipe2.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/09/04 17:31
 ************************************************************************/

#include <iostream>
#include <string>
#include <unistd.h>
#include <cassert>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE 1024

int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n != -1);
    (void)n;
#ifdef DEBUG
    std::cout << "pipefd[0]:" << pipefd[0] << std::endl;
    std::cout << "pipefd[1]:" << pipefd[1] << std::endl;
#endif 
    pid_t id = fork();
    assert(id != -1);
    if (id == 0) {
        close(pipefd[1]);
        char buffer[BUFFER_SIZE];
        while (1) {
            sleep(10);
            ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1);
            if (s > 0) {
                buffer[s] = 0;
                std::cout << "Child get a message[" << getpid() << "] Father# " << buffer << std::endl;
            } else if (s == 0) {
                std::cout << "Writer quit, I am going to quit." << std::endl;
                break;
            }
        }
        exit(0);
    }
    close(pipefd[0]);
    std::string message = "Father process is sendint message to child process.";
    int cnt = 0;
    char send_buffer[BUFFER_SIZE];
    while (1) {
        snprintf(send_buffer, sizeof send_buffer, "%s[%d]:%d", message.c_str(), getpid(), ++cnt);
        write(pipefd[1], send_buffer, strlen(send_buffer));
        std::cout << cnt << std::endl;
    }
    close(pipefd[1]);
    pid_t res = waitpid(id, nullptr, 0);
    assert(res > 0);
    (void)res;
    return 0;
}
